<template>
  <div class="container">
    <div class="mx-auto mt-lg-10" style="max-width: 400px">
      <v-card-text class="text-center">
        <v-img class="mx-auto" :src="require('@/assets/logo1.png')" width="250"></v-img>
        <v-card-subtitle class="font-weight-bold text-h6">
          Login to get the Real-time service.
        </v-card-subtitle>
      </v-card-text>
      <v-form ref="form">
        <v-text-field
          outlined
          color="green"
          v-model="email"
          :rules="emailRules"
          label="E-mail"
          required
        ></v-text-field>
        <v-text-field
          outlined
          color="green"
          v-model="code"
          :rules="codeRules"
          label="Verify code"
          :counter="4"
          required
        >
          <v-btn slot="append" small depressed color="red lighten-1"
           class="white--text"
           :disabled="codeDisabled"
           @click="handleSendCode"
          >{{ buttonText }}</v-btn>
        </v-text-field>
        <v-card-actions class="px-0">
          <v-btn block depressed large dark color="red lighten-1"
            @click="submit"
          >
            Login without registration
          </v-btn>
        </v-card-actions>
      </v-form>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { Dialog } from 'vant';
import { sendEmailCode } from '@/api/login';
import { param2Obj } from '@/utils/help';
import { ERROR_OK } from '@/api/config';

Vue.use(Dialog);
const COUNT = 60;
export default Vue.extend({
  name: 'Login',
  data: () => ({
    email: '',
    emailRules: [
      (v) => !!v || 'E-mail is required',
      (v) => /.+@.+\..+/.test(v) || 'E-mail must be valid',
    ],
    code: '',
    codeRules: [
      (v) => v.length === 4 || 'error',
    ],
    codeDisabled: false,
    buttonText: 'send code',
    count: COUNT,
    timer: null,
    redirect: undefined,
  }),
  watch: {
    $route: {
      // eslint-disable-next-line
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    handleSendCode() {
      this.buttonText = 'loading';
      this.codeDisabled = true;
      sendEmailCode({ email: this.email }).then((res) => {
        if (res.code === ERROR_OK) {
          Dialog.alert({
            title: 'Mail sent successfully',
            confirmButtonText: 'Confirm',
            message: "For this login to your email, please check your inbox. If you can't find it, please check your spam,if you have any questions,please free to contact us.",
          }).then(() => {
            // on close
          });
          if (!this.codeDisabled) {
            this.codeDisabled = true;
          }
          this.start();
        } else {
          this.buttonText = 'send code';
          this.codeDisabled = false;
        }
      }).catch(() => {
        this.buttonText = 'send code';
        this.codeDisabled = false;
      });
    },
    start() {
      this.timer && clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.buttonCount();
      }, 1000);
      this.buttonCount();
    },
    stop() {
      this.timer && clearInterval(this.timer);
      delete this.timer;
      this.count = COUNT;
      this.buttonText = 'send code';
      this.codeDisabled = false;
    },
    buttonCount() {
      if (this.count) {
        this.buttonText = `Countdown(${this.count})`;
      } else {
        this.stop();
      }
      this.count -= 1;
    },
    cleanArray(actual) {
      const newArray = [];
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
          newArray.push(actual[i]);
        }
      }
      return newArray;
    },
    param(json) {
      if (!json) return '';
      return this.cleanArray(
        Object.keys(json).map((key) => {
          if (json[key] === undefined) return '';
          return `${encodeURIComponent(key)}=${encodeURIComponent(json[key])}`;
        }),
      ).join('&');
    },
    submit() {
      if (this.$refs.form.validate()) {
        const { redeemCode, ...data } = param2Obj(window.location.search);
        this.$store.dispatch('user/login', { account: this.email, code: this.code, redeemCode })
          .then(() => {
            window.location.search = this.param(data);
            this.$router.push({ path: this.redirect || '/' });
          });
      }
    },
  },
});
</script>
